using System;
using System.Globalization;
using jSLCore.Utility.Extensions;

namespace jSLCore.Client.Presentation.jBinding.BaseConverters.MathConverters
{
    public abstract class jMathBaseConverter : jChainConverter
    {
        public override Type ThisType
        {
            get { return typeof (double); }
        }

        public double Operand { get; set; }

        public override object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value == null) return null;

            return DoOperation(value);
        }

        private object DoOperation(object value)
        {
            var sourceType = value.GetType();
            double val;
            if(double.TryParse(value.ToString(),out val))
            {
                var result = Process(val, Operand);
                return result.CastOrConvert(sourceType);
            }
            throw new InvalidCastException("Can not understand source value as double value");
        }
        //can't see how to merge it, delegating? or bool parameter.. it's not true...todo:...
        private object DoBackOperation(object value)
        {
            var sourceType = value.GetType();
            double val;
            if (double.TryParse(value.ToString(), out val))
            {
                var result = ProcessBack(val, Operand);
                return result.CastOrConvert(sourceType);
            }
            throw new InvalidCastException("Can not understand source value as double value");
        }

        public override object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value == null) return null;

            return DoBackOperation(value);
            
        }

        public abstract double Process(double value, double operand);
        public abstract double ProcessBack(double value, double operand);
    
    }
}